$(function () {
    cght_init();
})


function cght_init() {
    //采购方公司加载
    $("[name='cght_ssgs']").jgbmtree($("[name='cght_ssbm']"), $("[name='cght_cjr']"), '', '')

    //合作方加载
    $("[name='cght_gys']").qyjgzcombobox();
    var options = getCghtGridOption("");
    $('#cght-grid').datagrid(options);
}

function cght_search() {
    var zt = $("#cght-toolbar input[name='cght_zt']").val();
    var htbh = $("#cght-toolbar input[name='cght_htbh']").val();
    var gys = $("#cght-toolbar input[name='cght_gys']").val();
    var xhtbm = $("#cght-toolbar input[name='xsxt_htbm']").val();
    var startDate = $('#qdrq_start').datebox('getValue');
    var endDate = $('#qdrq_end').datebox('getValue');
    var ssgs = $("#cght-toolbar input[name='cght_ssgs']").val();
    var ssbm = $("#cght-toolbar input[name='cght_ssbm']").val();
    var cgr = $("#cght-toolbar input[name='cght_cjr']").val();
//    var kh = $("#xy-toolbar input[name='xy_kh']").val();
//    var spzt = $("#xy-toolbar input[name='xy_spzt']").val();
    $('#cght-grid').datagrid('load',
        {
            zt: zt,
            htbh: htbh,
            hzfId: gys,
            xhtbm: xhtbm,
            startDate: startDate,
            endDate: endDate,
            ssgsId: ssgs,
            ssbmId: ssbm,
            cgrId: cgr
        }
    );
}

var cghthref;
var isEdit;
var cght_win;
//新增采购合同
/*function cght_addItem(title, action) {
    var tit = "选择计划";
    var button = [
        {text: '确认', handler: function () {
            var href = $.webPath() + "/htgl/cghtgl/cghtgl_content?ljId=" + $("#ljId").val() + "&&jhId=" + $("#jhId").val();
            cghthref = $.webPath() + "/htgl/cghtgl/" + action;
            $(cght_win).window('close');
            cght_showDialog(title, href, "");
        }}
    ];
    cght_win = $.window({
        title: tit,
        iconCls: 'icon-add2',
        url: $.webPath() + "/htgl/cghtgl/cght_into",
        buttons: button,
        width: 1024,
        height: 500,
        model: true,
        maximizable: true,
        maximized: true,
        isMax: true
    });
}*/
function cght_addItem(title, action) {
    var href = $.webPath() + "/htgl/cghtgl/cghtgl_content";
    cghthref = $.webPath() + "/htgl/cghtgl/" + action;
    isEdit = "no";
    cght_showDialog(title, href, "");
}


//采购合同审核
function cght_confrim(title, action) {
    var record = $("#cght-grid").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择需要的记录!", "warning");
        return;
    }
    var href = $.webPath() + "/htgl/cghtgl/cght_print?cghtId=" + record.id;
    var tit = "采购合同审核";

    var button = [
        {text: '审核通过', handler: function () {
            cghtConfrimToAction(record.id, "yes");
        }},
        {text: '驳回', handler: function () {
            cghtConfrimToAction(record.id, "no");
        }}
    ];
    cght_win = $.window({
        title: tit,
        iconCls: 'icon-add2',
        url: href,
        buttons: button,
        width: 1024,
        height: 500,
        model: true,
        maximizable: true,
        maximized: true,
        isMax: false
    });


}

function cghtConfrimToAction(cghtId, shzt) {
    var actionUrl = $.webPath() + "/htgl/cghtgl/cght_confrim";
    $.post(actionUrl, {cghtId: cghtId, shzt: shzt}, function (data) {
        var obj = eval('(' + data + ')');
        $(cght_win).window('close');
        $('#cght-grid').datagrid('reload');
        $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
    })
}

function cght_editItem(title, action) {
    var record = $("#cght-grid").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要修改的记录!", "info");
        return;
    }
    var href = $.webPath() + "/htgl/cghtgl/cghtgl_content?cghtId=" + record.id;
    cghthref = $.webPath() + "/htgl/cghtgl/" + action;
    isEdit = "yes";
    cght_showDialog(title, href, record.zt_bz);
}

var cght_win;


function cght_htck(title, action) {
    var record = $("#cght-grid").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择需要的记录!", "warning");
        return;
    }
    var href = $.webPath() + "/htgl/cghtgl/cght_print?cghtId=" + record.id;
    var actionUrl = $.webPath() + "/htgl/cghtgl/" + action;
    cght_showPrintDialog(title, href, actionUrl);
}

function cght_showPrintDialog(title, href, actionUrl) {
    var win = $.window({
        title: "核查合同",
        width: 1024,
        height: 500,
        cache: false,
        url: href,
        modal: true,
        maximizable: true
    });
}


//新增、修改采购合同弹出界面
function cght_showDialog(title, href, cghtzt) {
    var button
    if (cghtzt == '已保存')
        button = [
            {text: '保存', handler: cght_saveItem}
        ];
    else
        button = [
            {text: '保存', handler: cght_saveItem}
        ];

    cght_win = $.window({
        title: title,
        iconCls: 'icon-add2',
        url: href,
        width: 1200,
        height: 550,
        buttons: button,
        onBeforeClose: function () {
            window.parent.destroy('cght-uploadify');
        }
    });
}

function cght_saveItem() {
    $(cght_win).mask();
    $("#cght_mx").edatagrid('saveRow');
    $('#cghtglForm').tabs('select', "合同信息");
    $("#cghtglForm").form('submit', {
        url: cghthref,
        onSubmit: function (param) {
            var validate = $(this).form('validate');
            if (!validate) {
                $('#cghtglForm').tabs('select', "合同信息");
                $.messager.alert("提示", "请填写必填项!", "waring");
                $(cght_win).mask('hide');
                return false;
            }
            var data = $('#cght_mx').edatagrid("getData");
            //验证明细是否填写
          /*  if (!data.rows.length) {
                $(cght_win).mask('hide');
                $('#cghtglForm').tabs('select', "合同明细");
                $.messager.alert("提示", "请填写合同明细!", "waring");
                return false;
            }*/
            //取的合同明细
            var arrayPrefix = 'cght.htmxList';
            // var fkfsPrefix = "cght.bgFkfs";
            var arrayParam = new Array();
            for (var i = 0; i < data.rows.length; i++) {
                //验证每行记录的合法性
              /*  if (data.rows[i].sbsl == 0 || data.rows[i].sbsl == null) {
                    $('#cghtglForm').tabs('select', "合同明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的数量不能为0 !', 'info');
                    $(cght_win).mask('hide');
                    return false;
                } else if (data.rows[i].hsj == 0 || data.rows[i].hsj == null) {
                    $('#cghtglForm').tabs('select', "合同明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的含税价不能为0 !', 'info');
                    $(cght_win).mask('hide');
                    return false;
                } else if (data.rows[i].bhsj == 0 || data.rows[i].bhsj == null) {
                    $('#cghtglForm').tabs('select', "合同明细");
                    $.messager.alert('提示', '第' + (i + 1) + '行的不含税价不能为0 !', 'info');
                    $(cght_win).mask('hide');
                    return false;
                }*/
//                else if (data.rows[i]['xsxt_xsdh'] == null || data.rows[i]['xsxt_xsdh'] == '') {
//                    $('#cghtglForm').tabs('select', "合同明细");
//                    $.messager.alert('提示', '第' + (i + 1) + '行的销售系统子项号不能为空 !', 'info');
//                    $(cght_win).mask('hide');
//                    return false;
//                }
                var rowStr = $.toJSONStringPrefix(data.rows[i], arrayPrefix + "[" + i + "].");
                arrayParam.push(rowStr.substring(1, rowStr.length - 1));
            }
            $.extend(param, $.parseJSON("{" + arrayParam.join(",") + "}"));
            return $(this).form('validate');
        },
        success: function (data) {
            $(cght_win).mask('hide');
            var obj = eval('(' + data + ')');
            if (obj.statusCode == '200') {
                if (isEdit == "yes") {
                    $(cght_win).window('close');
                    $('#cght-grid').datagrid('reload');
//                    $('#cght_layout').layout('panel', 'center').panel('refresh');
                    $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                } else {
//                    $.messager.confirm('确认', '是否编辑合同文本', function (r) {
//                        if (r) {
//                            $(cght_win).window('close');
//                            $('#cght-grid').datagrid('reload');
//                            $('#cght_layout').layout('panel', 'center').panel('refresh');
//                            $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
//                            var href = $.webPath() + "/htgl/cghtgl/cghtgl_content?cghtId=" + obj.cghtId;
//                            cghthref = $.webPath() + "/htgl/cghtgl/edit_cght";
//                            isEdit="yes";
//                            cght_showDialog("修改采购合同", href, "已保存");
////                            $('#cghtglForm').tabs('select', "合同文本");
//                        } else {
                    $(cght_win).window('close');
                    $('#cght-grid').datagrid('reload');
//                    $('#cght_layout').layout('panel', 'center').panel('refresh');
                    $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
//                        }
//                    });
                }

            } else {
                $(cght_win).mask('hide');
                $.messager.alert('提示', obj.message, 'info');
            }
        }
    });
}

function cght_commitItem() {
    var record = $("#cght-grid").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要提交的合同!", "info");
        return;
    }
    var message = "是否确认提交此采购合同";
    if (record.cglx == "直达到货") {
        message = "直达到货采购合同提交后，自动提交销售合同。提交后无法修改销售合同内容，是否确认提交";
    }
    $.messager.confirm('确认', message, function (r) {
        if (r) {
            $.post($.webPath() + '/htgl/cghtgl/commit_cght', {cghtId: record.id}, function (data) {
                var obj = eval('(' + data + ')');
                if (obj.statusCode == '200') {
                    $('#cght-grid').datagrid('reload');
//                    $('#cght_layout').layout('panel', 'center').panel('refresh');
                    if ($("[name='cght.id']").val() != null)
                        $(cght_win).window('close');
                    $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                } else
                    $.messager.alert('提示', obj.message, 'info');
            });
        }
    });
}




function cght_tj1() {
    var row = $('#cght-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否提交!', function (r) {
            if (r) {
                var index = $('#cght-grid').datagrid('getRowIndex', row);
                $.post($.webPath() + '/htgl/cghtgl/tj_cght', {cghtId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#cght-grid').datagrid('reload');
                        $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要提交的采购合同!", 'info');
    }
}



function cght_destroyItem() {
    var row = $('#cght-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否确认删除此采购合同', function (r) {
            if (r) {
                var index = $('#cght-grid').datagrid('getRowIndex', row);
                $.post($.webPath() + '/htgl/cghtgl/delete_cght', {cghtId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#cght-grid').datagrid('deleteRow', index);
                        $('#cght-grid').datagrid('reload');
//                        $('#cght_layout').layout('panel', 'center').panel('refresh');
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要删除的采购合同", 'info');
    }
}

function cght_tj_ck() {
    var row = $('#cght-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '是否提交仓储系统!', function (r) {
            if (r) {
                var index = $('#cght-grid').datagrid('getRowIndex', row);
                $.post($.webPath() + '/htgl/cghtgl/cght_tj_ck', {cghtId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#cght-grid').datagrid('reload');
                        $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要提交到仓储的采购合同!", 'info');
    }
}

function cght_agreeItem() {
    var row = $('#cght-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '合同履约后无法开单，是否确认履约此采购合同', function (r) {
            if (r) {
                $.post($.webPath() + '/htgl/cghtgl/agree_cght', {cghtId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#cght-grid').datagrid('reload');
//                        $('#cght_layout').layout('panel', 'center').panel('refresh');
                        $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要履约的采购合同", 'info');
    }
}

function cght_stopItem() {
    var row = $('#cght-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('确认', '合同终止后无法开单，是否确认终止此采购合同', function (r) {
            if (r) {
                $.post($.webPath() + '/htgl/cghtgl/stop_cght', {cghtId: row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#cght-grid').datagrid('reload');
//                        $('#cght_layout').layout('panel', 'center').panel('refresh');
                        $.messager.show({title: '提示框', msg: obj.message, timeout: 3000, showType: 'slide'});
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要终止的采购合同", 'info');
    }
}

function getCghtGridOption(type) {
    var options = {
        url: $.webPath() + "/htgl/cghtgl/cghtList",
        toolbar: "#cght-toolbar",
        fitColumns: true,
        singleSelect: true,
        pagination: true,
        pageNumber: 1,
        fit: true,
        rownumbers: true,
        onLoadSuccess: function (target) {
            $("#cght-del").css('display', 'none');
            $("#cght-edit").css('display', 'none');
            $("#cght-commit").css('display', 'none');
            $("#cght-agree").css('display', 'none');
            $("#cght-stop").css('display', 'none');
            $(this).datagrid('selectRow', 0);

            $(".datagrid-htable .datagrid-cell").css('text-align', 'center');

        },
        loadFilter: function (data) {
            $.each(data.rows, function () {
//                if (this.ckzt) {
//                    this.ckzt = this.ckzt == 0 ? "未上传" : this.ckzt == 1 ? "上传成功" : this.ckzt == 2 ? "上传失败" : "未上传";
//                }
                if (this.ckzt == 0) {
                    this.ckzt = "未上传";
                } else if (this.ckzt == 1) {
                    this.ckzt = "上传成功";
                } else if (this.ckzt == 2) {
                    this.ckzt = "上传失败";
                }
                if (this.cglx) {
                    this.cglx = this.cglx == "cgrk" ? "采购入库" : this.cglx == "zddh" ? "直达到货" : "统配合同";
                }
                if (this.zt) {
                    this.zt = this.zt == 'yly' ? "已完结" : this.zt == 'yzz' ? "已终止" : this.zt == 'ytj' ? "已提交" : this.zt == 'ysp' ? "已审批" : "已保存";
                }
                if (!this.wlyl)
                    this.wlyl = 0;
                this.wlyl = this.sbsl - this.wlyl;
            })

            return data;
        },
        onSelect: function (rowIndex, rowData) {
            if (!rowData) {
                $("#cght-commit").css('display', 'none');
                $("#cght-edit").css('display', 'none');
                $("#cght-del").css('display', 'none');
                $("#cght-agree").css('display', 'none');
                $("#cght-stop").css('display', 'none');
                $("#cght-tj-ck").hide();
                $("#cght_confrim").hide();
//                $('#cght_layout').layout('remove', 'center');
                return;
            }
            if (rowData && rowData.zt == '已保存') {
                $("#cght-edit").css('display', '');
                $("#cght-del").css('display', '');
                $("#cght-commit").css('display', '');
                $("#cght-agree").css('display', 'none');
                $("#cght-stop").css('display', 'none');
                $("#cght-tj-ck").hide();
                $("#cght_confrim").hide();
            /*    if(rowData && rowData.htms=='xsms'){

                    $("#cght-tj").show();
                    $("#cght-commit").css('display', 'none');
                }else{
                    $("#cght-tj").hide();
                }*/
            } else if (rowData && rowData.zt == '已提交') {
                $("#cght-edit").css('display', 'none');
                $("#cght-del").css('display', 'none');
                $("#cght-commit").css('display', 'none');
                $("#cght-agree").css('display', 'none');
                $("#cght-stop").css('display', 'none');
                $("#cght_confrim").show();
                $("#cght-tj-ck").hide();
               // $("#cght-tj").hide();
            } else if (rowData.zt == '已审批') {
                $("#cght-edit").css('display', 'none');
                $("#cght-del").css('display', 'none');
                $("#cght-commit").css('display', 'none');
                $("#cght-agree").css('display', '');
                $("#cght-stop").css('display', '');
                $("#cght_confrim").hide();
                if (rowData && rowData.ckzt == '未上传') {
                    $("#cght-tj-ck").show();
                } else if (rowData && rowData.ckzt == "上传成功") {
                    $("#cght-tj-ck").hide();
                } else if (rowData && rowData.ckzt == "上传失败") {
                    $("#cght-tj-ck").show();
                }
               // $("#cght-tj").hide();
            } else {
                $("#cght-commit").css('display', 'none');
                $("#cght-edit").css('display', 'none');
                $("#cght-del").css('display', 'none');
                $("#cght-agree").css('display', 'none');
                $("#cght-stop").css('display', 'none');
                $("#cght-tj-ck").hide();
                $("#cght_confrim").hide();
            }
        },
        onDblClickCell: function (index, field, value) {
            if (field == "htbm") {
                $("#cght-edit:visible").click();
//                var record = $("#cght-grid").datagrid("getSelected")
//                if (record.zt == '已保存')
//                    cght_editItem('修改采购合同', 'edit_cght');
            }
        }
    };
    if (type == "cgrk") {
        var columns = {columns: [
            [
                {field: 'htbm', title: '合同号', align: 'center', width: 50, formatter: cghtCell},
                {field: 'hzf_qc', title: '供应商', align: 'center', width: 50},
                {field: 'htms', title: '合同模式', align: 'center',formatter: function (value) {
                    if (value == 'xsms') {
                        return "线上"
                    } else {
                        return "线下"
                    }
                }, width: 30},
                {field: 'cglx', title: '类型', align: 'center', width: 20},
                {field: 'sbsl', title: '重量', align: 'right',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'wlyl', title: '未履约量', align: 'right',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'sbgs_jc', title: '申报公司', align: 'center', width: 30},
                {field: 'sbr_xm', title: '申报人', align: 'center', width: 20},
                {field: 'qdrq', title: '签订日期', align: 'center', width: 30},
                {field: 'zt', title: '状态', width: 20, align: 'center', formatter: formatCghtSp},
                {field: 'ckzt', title: '上传仓储', width: 20, align: 'center'}
            ]
        ]}
        options = $.extend(options, columns);
    } else if (type == "zddh") {
        var columns = {columns: [
            [
                {field: 'htbm', title: '合同号', align: 'center', width: 50, formatter: cghtCell},
                {field: 'hzf_qc', title: '供应商', align: 'center', width: 50},
                {field: 'htms', title: '合同模式', align: 'center',formatter: function (value) {
                    if (value == 'xsms') {
                        return "线上"
                    } else {
                        return "线下"
                    }
                }, width: 30},
                {field: 'extension', title: '是否居中结算订单', align: 'center',formatter: function (value) {
                    if (value == 'mid') {
                        return "是"
                    } else {
                        return "否"
                    }
                }, width: 15},
                {field: 'cglx', title: '类型', align: 'center', width: 20},
                {field: 'sbsl', title: '重量', align: 'right',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'wlyl', title: '未履约量', align: 'right',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'sbgs_jc', title: '申报公司', align: 'center', width: 30},
                {field: 'sbr_xm', title: '申报人', align: 'center', width: 20},
                {field: 'qdrq', title: '签订日期', align: 'center', width: 30},
                //{field: 'jsrq', title: '结束日期', width: 30},
                {field: 'xsht_htbm', title: '销售合同', align: 'center', width: 50},
                {field: 'zt', title: '状态', width: 20, align: 'center', formatter: formatCghtSp},
                {field: 'ckzt', title: '上传仓储', width: 20, align: 'center'}
            ]
        ]}
        options = $.extend(options, columns);
    } else {
        var columns = {columns: [
            [
                {field: 'htbm', title: '合同号', align: 'center', width: 50, formatter: cghtCell},
                {field: 'xsxt_htbm', title: '来源系统合同号', align: 'center', width: 50},
                {field: 'hzf_qc', title: '供应商', align: 'center', width: 90},
                {field: 'htms', title: '合同模式', align: 'center',formatter: function (value) {
                    if (value == 'xsms') {
                        return "线上"
                    } else {
                        return "线下"
                    }
                }, width: 30},
                {field: 'extension', title: '是否居中结算订单', align: 'center',formatter: function (value) {
                    if (value == 'mid') {
                        return "是"
                    } else {
                        return "否"
                    }
                }, width: 20},
                {field: 'cglx', title: '类型', align: 'center', width: 40},
                {field: 'sbsl', title: '重量', align: 'right',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 40},
                {field: 'wlyl', title: '未履约量', align: 'right',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    }, width: 40},
                {field: 'sbgs_jc', title: '申报公司', align: 'center', width: 40},
                {field: 'sbr_xm', title: '申报人', align: 'center', width: 20},
                {field: 'qdrq', title: '签订日期', align: 'center', width: 30},
                //{field: 'jsrq', title: '结束日期', width: 30},
                {field: 'zt', title: '状态', width: 20, align: 'center', formatter: formatCghtSp},
                {field: 'ckzt', title: '上传仓储', width: 20, align: 'center'}
            ]
        ]}
        options = $.extend(options, columns);
    }
    return options;
}


function formatCghtSp(val, row) {
    if (!row.processInstanceId || row.cglx == '统配合同') {
        return val;
    } else {
        return '<a href="javascript:viewCghtFlowPicture();" style="color: red">' + val + '</a>';
    }
}

function viewCghtFlowPicture() {
    var row = $('#cght-grid').datagrid('getSelected');
    $.window({
        title: "流程历史",
        iconCls: 'icon-add2',
        url: $.webPath() + "/flow/publish/flowPicture?processInstanceId=" + encodeURI(encodeURI(row.processInstanceId)) + "&businessNo=" + row.htbm,
        width: 650,
        height: 500,
        closed: true,
        modal: true,
        isMax: true
    });
}


